<template>
  <div class="header-user">
    <div v-if="user.isLogin" class="header-user-content">
      <i class="header-user-avatar"></i>
      <a-dropdown v-model="visible">
        <a class="ant-dropdown-link" href="javascript:">
          {{ user.info.name }}
          <a-icon type="down" :class="arrowClass" />
        </a>
        <a-menu slot="overlay">
          <a-menu-item v-for="(item, index) in user.menu" :key="index">
            <a
              v-if="item.action"
              href="javascript:"
              @click="doAction(item.action)"
              >{{ item.name }}</a
            >
            <a v-else :href="item.url" :target="item.target">{{ item.name }}</a>
          </a-menu-item>
          <a-menu-item @click="handleLogout">
            <a href="javascript:">退出</a>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </div>

    <div v-else class="header-user-login">
      <a href="javascript:" class="header-user-login-btn" @click="handleLogin"
        >登录</a
      >
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'IocUser',

  data() {
    return {
      visible: false
    }
  },

  computed: {
    ...mapState('global', {
      user: 'user',
      event: 'event'
    }),
    arrowClass() {
      const _class = ['header-user-arrow']

      if (this.visible) {
        _class.push('header-user-arrow--hover')
      }

      return _class
    }
  },

  methods: {
    handleLogin() {
      // this.event.handleLogin && this.event.handleLogin()
      Promise.resolve(this.event.handleLogin).then(next => {
        try {
          next().then(res => {
            this.$store.dispatch(this.$storeGlobalTypes.SET_USER_INFO, {
              isLogin: true,
              ...res
            })
          })
        } catch (e) {}
      })
    },
    handleLogout() {
      Promise.resolve(this.event.handleLogout).then(next => {
        try {
          next().then(() => {
            this.$store.dispatch(this.$storeGlobalTypes.SET_USER_INFO, {
              isLogin: false,
              info: {},
              menu: []
            })
            // 跳转到网关登出地址
            window.location.href =
              '/_tif_logout?returnUrl=https://gov-dev.pdcts.com.cn/citycode_m/'
          })
        } catch (e) {}
      })
    },
    doAction(action) {
      action && action(JSON.parse(JSON.stringify(this.user)))
    }
  }
}
</script>

<style lang="scss" src="./index.scss"></style>
